﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace scheduler
{
    public class Scheduler
    {
        private List<string> todoLists;
        private DateTime lastCheckTime;

        public List<string> TodoLists
        {
            get { return new List<string>(todoLists); }
        }

        public Scheduler()
        {
            todoLists = new List<string>(App.Settings.LoadTodoLists());

            var sLastCheckTime = App.Settings["LastCheckTime"].StringValue;
            if (!string.IsNullOrEmpty(sLastCheckTime))
            {
                lastCheckTime = DateTime.ParseExact(sLastCheckTime,
                        "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
            }
        }

        public bool AddTodoList(string file)
        {
            if (todoLists.Contains(file))
            {
                return false;
            }
            todoLists.Add(file);
            return true;
        }

        public void RemoveTodoList(string file)
        {
            var removed = todoLists.Remove(file);
        }

        public void SaveChanges()
        {
            App.Settings.SaveTodoLists(new List<string>(todoLists));
        }

        public void Check()
        {
            var now = DateTime.Now;
            foreach (var todoList in todoLists)
            {
                try
                {
                    new RemindChecker(todoList).Check(lastCheckTime, now);
                }
                catch (FileNotFoundException e)
                {
                    // remove from todoLists..
                }
            }
            lastCheckTime = now;
            App.Settings["LastCheckTime"].StringValue = lastCheckTime.ToString("yyyy-MM-dd HH:mm");
        }

        public bool ContainsTodoList(string fileName)
        {
            return todoLists.Contains(fileName);
        }
    }
}